﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine.AddressableAssets;
using UnityEngine;
using UnityEngine.ResourceManagement.AsyncOperations;
using System.Threading.Tasks;

public class AddressablesExample : MonoBehaviour
{
    GameObject go;

    [SerializeField]
    private AssetReference _asset;
    private GameObject _instance;

    private void Start()
    {
        Load2();
    }
    void OnGUI()
    {
        if(GUI.Button(new Rect(20, 140, 200, 100), "切换图片"))
        {
            ChangeSprite();
        }
    }

    #region 基础回调法
    private void Load1()
    {
        _asset.LoadAssetAsync<GameObject>().Completed += OnLoadedCompleted;
        _asset.InstantiateAsync().Completed += OnInstantiatedCompleted;
    }
    private void OnLoadedCompleted(AsyncOperationHandle<GameObject> obj)
    {
        Debug.Log($"Load {obj.Result.name} from async operation.");
    }
    private void OnInstantiatedCompleted(AsyncOperationHandle<GameObject> obj)
    {
        Debug.Log($"Instantiate {obj.Result.name} completed.");
    }
    #endregion

    #region await回调法
    private async void Load2()
    {
        _instance = await _asset.InstantiateAsync().Task;
    }
    #endregion

    private void OnDisable()
    {
        _asset.ReleaseInstance(_instance);
    }


    private int _skinIndex = 1;
    private int _matIndex = 1;

    public async void ChangeMaterial()
    {
        _matIndex = _matIndex == 1 ? 2 : 1;
        var mat = await Addressables.LoadAssetsAsync<Material>(
            new List<object> { "mat" }, 
            null, Addressables.MergeMode.None).Task;
        // 将返回的材质球赋值给加载的cube
        _instance.GetComponent<Renderer>().material = mat[_matIndex - 1];
    }
    public async void ChangeSprite()
    {
        _skinIndex = _skinIndex == 1 ? 2 : 1;
        var tex = await Addressables.LoadAssetsAsync<Texture>(
            new List<object> { "pic"},
            null, Addressables.MergeMode.None).Task;
        // 将返回的贴图赋值给加载的材质
        _instance.GetComponent<Renderer>().material.mainTexture = tex[_skinIndex - 1];
    }
}
